package com.rx.common.directive.sys;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.rx.util.DirectiveUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

/**
 * 权限标签
 * 
 * @author Renxin
 * 
 */
@Repository("privilege")
public class PrivilegeDirective implements TemplateDirectiveModel {

	/**
	 * 权限编号
	 */
	public static final String CODE = "code";

	@SuppressWarnings("unchecked")
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		// 获取参数
		String code = DirectiveUtils.getString(CODE, params);
		if (StringUtils.isEmpty(code)) {
			throw new TemplateModelException("The required \"" + CODE
					+ "\" paramter is missing.");
		}
		// 获取用户权限列表
		Set<String> userCodes = (Set<String>) Struts2Utils.getSession()
				.getAttribute("privilege_code");
		// 用户是否有用该权限
		if (userCodes.contains(code)) {
			body.render(env.getOut());
		}
	}

}
